package com.sky.service.impl;

import com.sky.dto.MerchantDTO;
import com.sky.dto.MerchantPageQueryDTO;
import com.sky.dto.MerchantStatusDTO;
import com.sky.dto.MerchantUpdateDTO;
import com.sky.dto.MerchantLoginDTO;
import com.sky.dto.MerchantChangePasswordDTO;
import com.sky.entity.Merchant;
import com.sky.exception.BaseException;
import com.sky.mapper.MerchantMapper;
import com.sky.service.MerchantService;
import com.sky.vo.MerchantAccountVO;
import com.sky.vo.MerchantOrderVO;
import com.sky.vo.PageResult;
import com.sky.vo.MerchantLoginVO;
import com.sky.vo.MerchantVO;
import com.sky.vo.MerchantAvatarVO;
import com.sky.vo.MerchantRevenueVO;
import com.sky.vo.MerchantRevenueVO.RevenueStatisticsItem;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;
import com.sky.utils.JwtUtil;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;

@Service
public class MerchantServiceImpl implements MerchantService {

    @Autowired
    private MerchantMapper merchantMapper;
    
    @Value("${sky.jwt.merchant-secret-key}")
    private String merchantSecretKey;
    
    @Value("${sky.jwt.merchant-ttl}")
    private Long merchantTtl;

    @Override
    public PageResult<Merchant> pageQuery(MerchantPageQueryDTO merchantPageQueryDTO) {
        // 计算分页参数
        int page = merchantPageQueryDTO.getPage();
        int pageSize = merchantPageQueryDTO.getPageSize();
        int start = (page - 1) * pageSize;
        merchantPageQueryDTO.setStart(start);

        // 查询商家列表
        List<Merchant> merchantList = merchantMapper.selectByPage(merchantPageQueryDTO);

        // 查询商家总数
        Integer total = merchantMapper.selectCount(merchantPageQueryDTO);

        return new PageResult<>((long)total, merchantList);
    }

    @Override
    public Map<String, Object> addMerchant(MerchantDTO merchantDTO) {
        // 检查用户名是否已存在
        Merchant existingMerchant = merchantMapper.selectByUsername(merchantDTO.getUsername());
        if (existingMerchant != null) {
            throw new BaseException("用户名已经存在！");
        }

        // 创建商家对象
        Merchant merchant = new Merchant();
        BeanUtils.copyProperties(merchantDTO, merchant);
        
        // 处理location字段 - 当location为null时使用address字段的值
        if (merchant.getLocation() == null && merchantDTO.getAddress() != null) {
            merchant.setLocation(merchantDTO.getAddress());
        }
        
        // 处理contact字段 - 当contact为null时使用contactNumber字段的值
        if (merchant.getContact() == null && merchantDTO.getContactNumber() != null) {
            merchant.setContact(merchantDTO.getContactNumber());
        }
        
        // 商家分类ID已在BeanUtils.copyProperties时设置，无需单独处理

        // 对密码进行MD5加密
        String encryptedPassword = DigestUtils.md5DigestAsHex(merchantDTO.getPassword().getBytes());
        merchant.setPassword(encryptedPassword);

        // 设置默认状态为待审核
        merchant.setStatus("pending");

        // 设置创建时间和更新时间
        merchant.setCreatedAt(LocalDateTime.now());
        merchant.setUpdatedAt(LocalDateTime.now());

        // 插入商家
        merchantMapper.insert(merchant);

        // 返回包含id的Map
        Map<String, Object> result = new HashMap<>();
        result.put("id", merchant.getId());
        return result;
    }

    @Override
    public Merchant getById(Long id) {
        Merchant merchant = merchantMapper.selectById(id);
        if (merchant == null) {
            throw new BaseException("商家不存在！");
        }
        return merchant;
    }

    @Override
    public String updateMerchant(Long id, MerchantUpdateDTO merchantUpdateDTO) {
        // 检查商家是否存在
        Merchant merchant = merchantMapper.selectById(id);
        if (merchant == null) {
            throw new BaseException("商家不存在！");
        }

        // 保存原始状态
        String originalStatus = merchant.getStatus();
        
        // 创建一个临时对象用于更新非状态字段
        Merchant tempMerchant = new Merchant();
        tempMerchant.setId(id);
        tempMerchant.setName(merchantUpdateDTO.getName());
        tempMerchant.setContact(merchantUpdateDTO.getContact());
        tempMerchant.setUsername(merchantUpdateDTO.getUsername());
        tempMerchant.setBusinessLicense(merchantUpdateDTO.getBusinessLicense());
        tempMerchant.setBankName(merchantUpdateDTO.getBankName());
        tempMerchant.setBankAccount(merchantUpdateDTO.getBankAccount());
        tempMerchant.setDescription(merchantUpdateDTO.getDescription());
        
        // 设置商家分类ID
        if (merchantUpdateDTO.getCategoryId() != null) {
            tempMerchant.setCategoryId(merchantUpdateDTO.getCategoryId());
        }
        
        tempMerchant.setUpdatedAt(LocalDateTime.now());
        
        // 更新非状态字段
        merchantMapper.update(tempMerchant);
        
        // 如果状态有变化，单独更新状态
        if (merchantUpdateDTO.getStatus() != null && !merchantUpdateDTO.getStatus().equals(originalStatus)) {
            // 使用Merchant对象直接更新状态
            Merchant statusUpdateMerchant = new Merchant();
            statusUpdateMerchant.setId(id);
            statusUpdateMerchant.setStatus(merchantUpdateDTO.getStatus());
            statusUpdateMerchant.setUpdatedAt(LocalDateTime.now());
            merchantMapper.update(statusUpdateMerchant);
            merchant.setStatus(merchantUpdateDTO.getStatus());
        }

        return "商家信息更新成功";
    }

    @Override
    public String deleteMerchant(Long id) {
        // 检查商家是否存在
        Merchant merchant = merchantMapper.selectById(id);
        if (merchant == null) {
            throw new BaseException("商家不存在！");
        }

        // 删除商家
        merchantMapper.deleteById(id);
        
        return "商家删除成功";
    }

    @Override
    public Merchant updateStatus(Long id, MerchantStatusDTO merchantStatusDTO) {
        // 检查商家是否存在
        Merchant merchant = merchantMapper.selectById(id);
        if (merchant == null) {
            throw new BaseException("商家不存在！");
        }

        // 使用Merchant对象直接更新，避免类型不匹配问题
        Merchant updateMerchant = new Merchant();
        updateMerchant.setId(id);
        updateMerchant.setStatus(merchantStatusDTO.getStatus());
        updateMerchant.setUpdatedAt(LocalDateTime.now());
        merchantMapper.update(updateMerchant);

        // 返回更新后的商家信息
        merchant.setStatus(merchantStatusDTO.getStatus());
        return merchant;
    }

    @Override
    public Map<String, Object> getMerchantOrders(Map<String, Object> params) {
        // 获取商家ID
        Long id = params.get("id") != null ? Long.valueOf(params.get("id").toString()) : null;
        
        if (id == null) {
            throw new BaseException("商家ID不能为空！");
        }
        
        // 检查商家是否存在
        Merchant merchant = merchantMapper.selectById(id);
        if (merchant == null) {
            throw new BaseException("商家不存在！");
        }

        // 设置商家ID
        params.put("merchantId", id);

        // 计算分页参数
        int page = params.get("page") != null ? (int) params.get("page") : 1;
        int pageSize = params.get("pageSize") != null ? (int) params.get("pageSize") : 10;
        int start = (page - 1) * pageSize;
        params.put("start", start);
        params.put("pageSize", pageSize);

        // 查询订单列表
        List<Map<String, Object>> orderList = merchantMapper.selectMerchantOrders(params);

        // 查询订单总数
        Integer total = merchantMapper.selectMerchantOrdersCount(params);

        // 查询总金额
        Double totalAmount = merchantMapper.selectTotalRevenueByMerchantId(id);
        if (totalAmount == null) {
            totalAmount = 0.0;
        }

        // 构建返回结果
        List<MerchantOrderVO> merchantOrderVOList = new ArrayList<>();
        for (Map<String, Object> orderMap : orderList) {
            MerchantOrderVO vo = new MerchantOrderVO();
            vo.setId(Long.valueOf(orderMap.get("id").toString()));
            vo.setOrderNo(orderMap.get("order_no") != null ? orderMap.get("order_no").toString() : "");
            vo.setDocumentName(orderMap.get("document_name") != null ? orderMap.get("document_name").toString() : "");
            vo.setOrderTime(orderMap.get("order_time") != null ? orderMap.get("order_time").toString() : "");
            vo.setAmount(orderMap.get("amount") != null ? new BigDecimal(orderMap.get("amount").toString()) : BigDecimal.ZERO);
            vo.setStatus(orderMap.get("status") != null ? orderMap.get("status").toString() : "");
            vo.setStudentName(orderMap.get("student_name") != null ? orderMap.get("student_name").toString() : "");
            vo.setStudentContact(orderMap.get("student_contact") != null ? orderMap.get("student_contact").toString() : "");
            merchantOrderVOList.add(vo);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("list", merchantOrderVOList);
        result.put("total", total);
        result.put("totalAmount", totalAmount);
        result.put("page", page);
        result.put("pageSize", pageSize);

        return result;
    }

    @Override
    public MerchantAccountVO getMerchantAccount(Long id) {
        // 检查商家是否存在
        Merchant merchant = merchantMapper.selectById(id);
        if (merchant == null) {
            throw new BaseException("商家不存在！");
        }

        // 查询总营收
        Double totalRevenue = merchantMapper.selectTotalRevenueByMerchantId(id);
        if (totalRevenue == null) {
            totalRevenue = 0.0;
        }

        // 构建商家账户信息
        MerchantAccountVO accountVO = new MerchantAccountVO();
        accountVO.setMerchantId(merchant.getId());
        accountVO.setMerchantName(merchant.getName());
        accountVO.setUsername(merchant.getUsername());
        accountVO.setStatus(merchant.getStatus());
        accountVO.setBankName(merchant.getBankName());
        accountVO.setBankAccount(merchant.getBankAccount());
        accountVO.setTotalIncome(merchant.getTotalIncome());
        accountVO.setBalance(merchant.getBalance());
        accountVO.setWithdrawalCount(merchant.getWithdrawalCount());
        accountVO.setFrozen(merchant.getFrozen());
        accountVO.setTotalRevenue(new BigDecimal(totalRevenue));
        accountVO.setCreatedAt(merchant.getCreatedAt().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        accountVO.setLastLoginTime(merchant.getLastLoginTime());
        accountVO.setLastWithdrawalTime(merchant.getLastWithdrawalTime());

        return accountVO;
    }

    @Override
    public MerchantLoginVO login(MerchantLoginDTO merchantLoginDTO) {
        String username = merchantLoginDTO.getUsername();
        String password = merchantLoginDTO.getPassword();
        
        // 查询商家
        Merchant merchant = merchantMapper.selectByUsername(username);
        if (merchant == null) {
            throw new BaseException("用户名或密码错误");
        }
        
        // 验证密码
        String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!encryptedPassword.equals(merchant.getPassword())) {
            throw new BaseException("用户名或密码错误");
        }
        
        // 检查商家状态
        if (!"active".equals(merchant.getStatus())) {
            throw new BaseException("商家账户未激活或已禁用");
        }
        
        // 更新最后登录时间
        merchant.setLastLoginTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        merchantMapper.update(merchant);
        
        // 生成JWT令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", merchant.getId());
        claims.put("username", merchant.getUsername());
        String token = JwtUtil.createJWT(merchantSecretKey, merchantTtl, claims);
        
        // 构建返回结果
        MerchantLoginVO loginVO = new MerchantLoginVO();
        loginVO.setToken(token);
        
        MerchantVO merchantVO = new MerchantVO();
        BeanUtils.copyProperties(merchant, merchantVO);
        loginVO.setMerchant(merchantVO);
        
        return loginVO;
    }

    @Override
    public MerchantVO updateSelfInfo(Long merchantId, MerchantDTO merchantDTO) {
        // 检查商家是否存在
        Merchant merchant = merchantMapper.selectById(merchantId);
        if (merchant == null) {
            throw new BaseException("商家不存在");
        }
        
        // 更新商家信息
        merchant.setName(merchantDTO.getName());
        merchant.setLocation(merchantDTO.getLocation());
        merchant.setContact(merchantDTO.getContact());
        merchant.setBankName(merchantDTO.getBankName());
        merchant.setBankAccount(merchantDTO.getBankAccount());
        merchant.setUpdatedAt(LocalDateTime.now());
        
        merchantMapper.update(merchant);
        
        // 构建返回结果
        MerchantVO merchantVO = new MerchantVO();
        BeanUtils.copyProperties(merchant, merchantVO);
        return merchantVO;
    }

    @Override
    public void changePassword(Long merchantId, MerchantChangePasswordDTO passwordDTO) {
        // 检查商家是否存在
        Merchant merchant = merchantMapper.selectById(merchantId);
        if (merchant == null) {
            throw new BaseException("商家不存在");
        }
        
        // 验证旧密码
        String encryptedOldPassword = DigestUtils.md5DigestAsHex(passwordDTO.getOldPassword().getBytes());
        if (!encryptedOldPassword.equals(merchant.getPassword())) {
            throw new BaseException("旧密码错误");
        }
        
        // 验证新密码和确认密码是否一致
        if (!passwordDTO.getNewPassword().equals(passwordDTO.getConfirmPassword())) {
            throw new BaseException("两次输入的新密码不一致");
        }
        
        // 更新密码
        String encryptedNewPassword = DigestUtils.md5DigestAsHex(passwordDTO.getNewPassword().getBytes());
        merchant.setPassword(encryptedNewPassword);
        merchant.setUpdatedAt(LocalDateTime.now());
        
        merchantMapper.update(merchant);
    }

    @Override
    public MerchantAvatarVO uploadAvatar(Long merchantId, MultipartFile file) {
        // 检查商家是否存在
        Merchant merchant = merchantMapper.selectById(merchantId);
        if (merchant == null) {
            throw new BaseException("商家不存在");
        }
        
        // 检查文件是否为空
        if (file.isEmpty()) {
            throw new BaseException("请选择要上传的头像文件");
        }
        
        // 确保商家信息文件夹存在
        String uploadDir = "f:/pro/飞印/原型8.8/后端/商家信息/";
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        
        // 生成文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename != null && originalFilename.contains(".") 
                ? originalFilename.substring(originalFilename.lastIndexOf(".")) 
                : ".jpg";
        String filename = "merchant_" + merchantId + "_" + System.currentTimeMillis() + extension;
        String filepath = uploadDir + filename;
        
        // 保存文件
        try {
            file.transferTo(new File(filepath));
        } catch (IOException e) {
            throw new BaseException("头像上传失败：" + e.getMessage());
        }
        
        // 更新商家头像路径
        merchant.setAvatar(filename); // 使用avatar字段存储头像
        merchantMapper.update(merchant);
        
        // 构建返回结果
        MerchantAvatarVO avatarVO = new MerchantAvatarVO();
        // 返回绝对路径
        avatarVO.setAvatarUrl("F:\\pro\\飞印\\原型8.8\\后端\\商家信息\\" + filename);
        
        return avatarVO;
    }

    @Override
    public MerchantVO pauseBusiness(Long merchantId) {
        // 检查商家是否存在
        Merchant merchant = merchantMapper.selectById(merchantId);
        if (merchant == null) {
            throw new BaseException("商家不存在");
        }
        
        // 只更新营业状态字段，不修改status字段
        merchant.setBusinessStatus("paused");
        merchant.setUpdatedAt(LocalDateTime.now());
        
        merchantMapper.update(merchant);
        
        // 构建返回结果
        MerchantVO merchantVO = new MerchantVO();
        BeanUtils.copyProperties(merchant, merchantVO);
        return merchantVO;
    }

    @Override
    public MerchantVO resumeBusiness(Long merchantId) {
        // 检查商家是否存在
        Merchant merchant = merchantMapper.selectById(merchantId);
        if (merchant == null) {
            throw new BaseException("商家不存在");
        }
        
        // 只更新营业状态字段，不修改status字段
        merchant.setBusinessStatus("operating");
        merchant.setUpdatedAt(LocalDateTime.now());
        
        merchantMapper.update(merchant);
        
        // 构建返回结果
        MerchantVO merchantVO = new MerchantVO();
        BeanUtils.copyProperties(merchant, merchantVO);
        return merchantVO;
    }

    @Override
    public MerchantRevenueVO getRevenue(Long merchantId, String startDate, String endDate, String type) {
        // 检查商家是否存在
        Merchant merchant = merchantMapper.selectById(merchantId);
        if (merchant == null) {
            throw new BaseException("商家不存在");
        }
        
        // 构建返回结果，直接使用商家对象中的实际数据
        MerchantRevenueVO revenueVO = new MerchantRevenueVO();
        
        // 设置总收入（从totalIncome字段获取）
        if (merchant.getTotalIncome() != null) {
            revenueVO.setTotalRevenue(merchant.getTotalIncome().doubleValue());
        } else {
            revenueVO.setTotalRevenue(0.0);
        }
        
        // 设置余额（从balance字段获取）
        if (merchant.getBalance() != null) {
            revenueVO.setBalance(merchant.getBalance().doubleValue());
        } else {
            revenueVO.setBalance(0.0);
        }
        
        // 设置提现次数（从withdrawalCount字段获取）
        if (merchant.getWithdrawalCount() != null) {
            revenueVO.setWithdrawalCount(merchant.getWithdrawalCount());
        } else {
            revenueVO.setWithdrawalCount(0);
        }
        
        // 可以设置一个估算的订单数量，或从其他查询中获取
        revenueVO.setTotalOrders(0);
        
        // 创建当天的统计项作为示例
        List<RevenueStatisticsItem> statistics = new ArrayList<>();
        RevenueStatisticsItem todayItem = new RevenueStatisticsItem();
        todayItem.setDate(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        todayItem.setRevenue(revenueVO.getTotalRevenue());
        todayItem.setOrders(0);
        statistics.add(todayItem);
        
        revenueVO.setStatistics(statistics);
        
        return revenueVO;
    }

    @Override
    public void logout(Long merchantId) {
        // 检查商家是否存在
        Merchant merchant = merchantMapper.selectById(merchantId);
        if (merchant == null) {
            throw new BaseException("商家不存在");
        }
        
        // 这里可以添加token失效的逻辑
        // 简化处理，直接返回成功
    }

    @Override
    public MerchantVO getCurrentMerchant(Long merchantId) {
        // 检查商家是否存在
        Merchant merchant = merchantMapper.selectById(merchantId);
        if (merchant == null) {
            throw new BaseException("商家不存在");
        }
        
        // 构建返回结果
        MerchantVO merchantVO = new MerchantVO();
        BeanUtils.copyProperties(merchant, merchantVO);
        
        // 对银行账号进行脱敏处理
        if (merchant.getBankAccount() != null && merchant.getBankAccount().length() >= 8) {
            String account = merchant.getBankAccount();
            String maskedAccount = account.substring(0, 4) + " **** **** **** " + 
                    account.substring(account.length() - 4);
            merchantVO.setBankAccount(maskedAccount);
        }
        
        return merchantVO;
    }



    public void auditMerchant(Long merchantId, MerchantStatusDTO merchantStatusDTO) {
        // 检查商家是否存在
        Merchant merchant = merchantMapper.selectById(merchantId);
        if (merchant == null) {
            throw new BaseException("商家不存在！");
        }

        // 更新状态
        merchant.setStatus(merchantStatusDTO.getStatus());
        merchant.setUpdatedAt(LocalDateTime.now());
        
        merchantMapper.update(merchant);
    }


    public List<Merchant> listMerchants() {
        // 创建一个查询DTO并设置合适的参数
        MerchantPageQueryDTO queryDTO = new MerchantPageQueryDTO();
        // 设置默认分页参数
        queryDTO.setPage(1);
        queryDTO.setPageSize(1000); // 设置一个合理的大值
        queryDTO.setStart(0);
        // 使用现有的selectByPage方法查询商家列表
        return merchantMapper.selectByPage(queryDTO);
    }


    public MerchantAccountVO getAccountInfo(Long merchantId) {
        return this.getMerchantAccount(merchantId);
    }
}